package io.iamting93.user.service;

import io.iamting93.api.CodeApi;
import io.iamting93.api.UserApi;
import io.iamting93.user.dao.TokenDao;
import io.iamting93.user.dao.UserDao;
import io.iamting93.user.pojo.Token;
import io.iamting93.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * @author boting.guo
 * @date 2021/11/30 17:05
 */

@Slf4j
@DubboService
public class UserService implements UserApi {

	@Autowired
	private TokenDao tokenDao;

	@DubboReference
	private CodeApi codeApi;

	@Autowired
	private UserDao userDao;

	public String register(String email, String password, String code) {
		// 核对验证码是否正确
		int result = codeApi.validateCode(email, code);
		// 验证码正确而且还没有注册
		if (result == 0 && !isRegistered(email)) {
			// 创建账号
			doRegister(email, password);
			// 创建令牌并且返回
			return createToken(email);
		}
		return null;
	}

	private void doRegister(String email, String password) {
		userDao.register(email, password);
	}

	public boolean isRegistered(String email) {
		User user = userDao.getUser(email);
		return user != null;
	}

	public String login(String email, String password) {
		// 根据email获取用户信息
		User user = userDao.getUser(email);
		// 简单匹配邮箱和密码
		if (user != null && user.getPassword().equals(password)) {
			// 成功就创建令牌
			return createToken(email);
		}
		return null;
	}

	@Override
	public String info(String t) {
		Token token = tokenDao.getTokenByEmail(t);
		if (token == null || token.getCreateTime() + 20 * 60 * 1000 < System.currentTimeMillis()) {
			return null;
		}
		return token.getEmail();
	}

	private String createToken(String email) {
		Token token = tokenDao.getToken(email);

		// 没有创建过或者已经过期
		if (token == null || token.getCreateTime() + 20 * 60 * 1000 < System.currentTimeMillis()) {
			token = new Token(email, UUID.randomUUID().toString(), System.currentTimeMillis());
			tokenDao.insertToken(token);
		}
		return token.getToken();
	}
}
